<!-- 账号管理 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px;">
      <div style="display:flex;justify-content:space-between;">
        <!-- <div class="title">账号管理列表</div> -->
        <div>
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">添加服务器</el-button>
        </div>
      </div>
      <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
        <el-table-column label="序号" width="60" type="index"
          :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
        <el-table-column label="服务器名称" prop="Name"  show-overflow-tooltip></el-table-column>
        <el-table-column label="服务器地址" show-overflow-tooltip prop="ServerIP" width="160px" ></el-table-column>
        <el-table-column label="登录用户名" show-overflow-tooltip prop="UserID" ></el-table-column>
        <el-table-column label="登录密码" show-overflow-tooltip prop="Pwd" ></el-table-column>
        <el-table-column label="应用对象类型" show-overflow-tooltip prop="DeviceObjType" width="120px">
          <template slot-scope="{row}">
            <span>{{ DeviceObjTypeFormatter(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应用对象" show-overflow-tooltip prop="DeviceObj" width="160px">
          <template slot-scope="{row}">
            <span>{{ getDeviceObjDisplay(row, DepartmentList, AssetsList) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"  width="150px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
            <el-button size="mini" type="danger" @click="deleteClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape=false :title="Action === 1 ? '添加服务器' : '修改服务器'"
      :visible.sync="dialogVisible" v-el-drag-dialog width="50%">
      <el-form label-width="120px" :model="accountForm" :rules="rules" ref="accountForm">
        <el-row class="ruleMain">
          <el-divider content-position="left">基本规则内容</el-divider>
          <el-form-item label='服务器昵称：' prop="Name">
            <el-input v-model="accountForm.Name" :disabled="Action !== 1" :maxlength="30"></el-input>
          </el-form-item>
          <el-form-item label='服务器地址：' prop="ServerIP">
            <el-input v-model="accountForm.ServerIP" oninput="value=value.replace(/[^0-9.]/g,'')"
              maxlength="15"></el-input>
          </el-form-item>
          <el-form-item label='登录用户名：' prop="UserID">
            <el-input v-model="accountForm.UserID"></el-input>
          </el-form-item>
          <el-form-item label='登录密码：' prop="Pwd">
            <el-input v-model="accountForm.Pwd"></el-input>
          </el-form-item>
          <device-object-selector :form.sync="accountForm" />
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import { getDeviceObjDisplay, DeviceObjTypeFormatter } from '@/utils/index.js';
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import DeviceObjectSelector from '@/components/DeviceObjectSelector'
export default {
  directives: { elDragDialog },
  components: {
    DeviceObjectSelector
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      ipList: [],
      portList: [],
      shopNameList: [],
      assetList: [],
      DeviceObjList: [],
      RoleList: [],
      AssetsList: [],
      DepartmentList: [],
      Action: 1,
      userIndex: 0,
      dialogVisible: false,
      accountForm: {},
      options: [],
      rules: {
        Name: [
          { required: true, message: "请输入服务器昵称" }
        ],
        ServerIP: [
          { required: true, message: "请输入服务器ip地址" },
          {
            validator: function (rule, value, callback) {
              if (/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test(value) == false && value) {
                callback(new Error("服务器地址格式错误，地址暂不支持英文"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        UserID: [
          { required: true, message: "请输入登录用户名" }
        ],
        Pwd: [
          { required: true, message: "请输入登录密码" }
        ],
      }
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.GetDepartment()
    this.GetDevice()
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {

  },
  methods: {
    DeviceObjTypeFormatter,
    getDeviceObjDisplay,
    // 获取所有部门
    async GetDepartment() {
      const res = await connrequest('GetDepartment')
      this.DepartmentList = res.Data
    },
    // 获取所有资产
    async GetDevice() {
      const data = {
        Paging: {
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
      }
      const res = await connrequest('GetDevice', data)
      this.AssetsList = res.Data
    },
    async getData() {
      const res = await connrequest('GetShareServerCfg')
      this.tableData = res.Data
    },
    addClick() {
      this.Action = 1
      let arr = [...this.tableData]
      let ipList = []
      let shopNameList = []
      arr.map(item => {
        ipList.push(item.ServerIP)
        shopNameList.push(item.Name)
      })
      this.ipList = ipList
      this.shopNameList = shopNameList
      this.dialogVisible = true
      this.$nextTick(() => {
        this.accountForm = { radio: 1, Employee: [], DeviceObjType: 1 }
        this.$refs['accountForm'].resetFields();
      })
    },
    changeClick(row, index) {
      this.userIndex = index
      this.Action = 2
      this.$nextTick(() => {
        this.accountForm = { ...row, Employee: row.Employee }
        this.$refs['accountForm'].resetFields();
      })
      let arr = [...this.tableData]
      arr.splice(index, 1)
      let ipList = []
      let shopNameList = []
      arr.map(item => {
        ipList.push(item.ServerIP)
        shopNameList.push(item.Name)
      })
      this.ipList = ipList
      this.shopNameList = shopNameList
      this.dialogVisible = true
    },
    deleteClick(row) {
      this.$confirm('此操作将永久删除该服务器, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.tableData.map((item, i) => {
          if (item.ServerIP === row.ServerIP) {
            this.tableData.splice(i, 1)
          }
        })
        let data = {
          Data: [
            ...this.tableData,
          ]
        }
        const res = await connrequest('SetShareServerCfg', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
          this.dialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    radioChange(value) {
      this.$set(this.accountForm, 'Employee', [])
    },
    submit() {
      this.$refs['accountForm'].validate(async (valid) => {
        if (valid) {
          if (this.shopNameList.indexOf(this.accountForm.Name) !== -1) {
            this.$message.error('该服务器昵称已经存在')
            return false
          } else if (this.ipList.indexOf(this.accountForm.ServerIP) !== -1) {
            this.$message.error('该服务器地址已经存在')
            return false
          } else if (this.accountForm.radio === 2 && this.accountForm.Employee.length === 0) {
            this.$message.error('指定资产不能为空')
            return false
          } else {
            if (this.Action === 1) {
              this.accountForm.Employee = this.accountForm.Employee || []
              this.tableData.push(this.accountForm)
            } else if (this.Action === 2) {
              this.tableData[this.userIndex] = this.accountForm
            }
            let data = {
              Data: [
                ...this.tableData,
              ]
            }
            const res = await connrequest('SetShareServerCfg', data)
            if (res.Status.StatusCode === 0) {
              this.getData()
              this.dialogVisible = false
            }
          }
        }
      })
    },
  }
}
</script>